package cn.innosmart.aq.view.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.DeviceActionsAdapter;
import cn.innosmart.aq.bean.ActionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.SceneBean;
import cn.innosmart.aq.bean.ScheduleBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * 用来显示可控制设备的列表界面
 * Created by David on 2015/8/17.
 */
public class AddActionActivity extends BaseActivity {
    private final int RULE = 2;
    private final int SCENE = 3;
    private final int UNKNOWN = -1;
    private final int SCHEDULE = 1;
    private final int SWITCHDEVICESCHEDULE = 1;
    private final int SWITCHSCENESCHEDULE = 2;
    private final int EXIT = 0;
    public AquariumBean aquariumBean;
    private ListView lv_actions;
    private ArrayList<String> actions;
    private DeviceActionsAdapter deviceActionsAdapter;
    private ArrayList<CommandBean> commandBeans;
    private String flag;
    private ScheduleBean scheduleBean;
    private SceneBean sceneBean;
    private ArrayList<ActionBean> commands;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
                case SWITCHDEVICESCHEDULE:
                    //排程中添加设备
                    String address = (String) msg.obj;
                    switchToScheduleActivity(address, 1);
                    break;
                case SWITCHSCENESCHEDULE:
                    //排程中添加场景
                    String sceneId = (String) msg.obj;
                    switchToScheduleActivity(sceneId, 2);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_action);
        String aquariumId = getIntent().getStringExtra("aquarium");
        if (aquariumId != null)
            aquariumBean = AquariumBean.findAquariumById(aquariumId);
        setBar();
        flag = getIntent().getStringExtra("flag");
        initialData();
        initView();
    }

    /**
     * 根据flag初始化参数
     * flag 场景 排程
     */
    private void initialData() {
        if (flag.equals("scene")) {
            actions = getIntent().getStringArrayListExtra("actions");
            if (actions == null)
                actions = new ArrayList<String>();
            sceneBean = SceneActivity.sceneBean;
            commands = sceneBean.getCommands();
            if (commands == null) {
                commands = new ArrayList<ActionBean>();
                sceneBean.setCommands(commands);
            }
        } else if (flag.equals("schedule")) {
            actions = getIntent().getStringArrayListExtra("actions");
            if (actions == null)
                actions = new ArrayList<String>();
            scheduleBean = new ScheduleBean();
            ArrayList<SceneBean> scenes = aquariumBean.getSceneList();
            for (SceneBean sceneBean : scenes) {
                actions.add(sceneBean.getId());
            }
        } else {
            actions = getIntent().getStringArrayListExtra("actions");
            if (actions == null)
                actions = new ArrayList<String>();
            commandBeans = RuleActivity.ruleBean.getCommands();
            if (commandBeans == null) {
                commandBeans = new ArrayList<CommandBean>();
                RuleActivity.ruleBean.setCommands(commandBeans);
            }
            ArrayList<SceneBean> scenes = aquariumBean.getSceneList();
            for (SceneBean sceneBean : scenes) {
                actions.add(sceneBean.getId());
            }
        }
    }

    private void initView() {
        lv_actions = (ListView) findViewById(R.id.lv_actions);
        if (!flag.equals("schedule")) {
            if (actions.size() == 0) {
            } else {
//                actions.add(getString(R.string.activity_action_for_alarm));
                actions.add(getString(R.string.activity_action_wait));
            }
            deviceActionsAdapter = new DeviceActionsAdapter(this, actions, RULE);
        } else {
            deviceActionsAdapter = new DeviceActionsAdapter(this, actions, SCHEDULE);
        }
        lv_actions.setAdapter(deviceActionsAdapter);
        lv_actions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String address = actions.get(position);
                if (flag.equals("schedule")) {
                    DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
                    if (deviceBean != null) {
                        Message msg = new Message();
                        msg.what = SWITCHDEVICESCHEDULE;
                        msg.obj = address;
                        mHandler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = SWITCHSCENESCHEDULE;
                        msg.obj = address;
                        mHandler.sendMessage(msg);
                    }
                } else {
                    if (position == actions.size() - 1) {
                        showSetActionDialog(new DeviceBean(), 2);
                    } else {
                        DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
                        if (deviceBean != null) {
                            showSetActionDialog(deviceBean, 1);
                        } else {
                            SceneBean sceneBean = SceneBean.queryScene(address);
                            if (flag.equals("rule")) {
                                CommandBean commandBean = new CommandBean();
                                commandBean.setOrder(commandBeans.size() + 1);
                                commandBean.setType("scene");
                                commandBean.setScene_id(address);
                                commandBeans.add(commandBean);
                                mHandler.sendEmptyMessage(EXIT);
                            }

                        }
                    }
                }
            }
        });
    }

    private void switchToScheduleActivity(String address, int type) {
        DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
        Intent intent = new Intent(AddActionActivity.this, ScheduleActivity.class);
        if (type == 1)
            intent.putExtra("device", deviceBean.getAddress());
        else if (type == 2)
            intent.putExtra("scene", address);
        intent.putExtra("aquarium", aquariumBean.getId());
        startActivity(intent);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        finish();
    }

    private void showSetActionDialog(final DeviceBean deviceBean, final int Type) {
        System.out.println("showSetActionDialog");
        System.out.println("Type:" + Type);
        System.out.println("deviceBean.getFunctype():" + deviceBean.getFunctype());

        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(this);
        customsizeDialog.setTitle(getString(R.string.fragment_rule_add_action_dialog_title));
        RadioButton rbOpen = (RadioButton) customsizeDialog.findViewById(R.id.rb_open);
        final RadioButton rbClose = (RadioButton) customsizeDialog.findViewById(R.id.rb_close);
        if (Type == 1) {
            if (DeviceConstant.FUNCTYPE_FEEDER == deviceBean.getFunctype()) {
                rbClose.setVisibility(View.GONE);
                rbOpen.setVisibility(View.VISIBLE);
            }
        }
        customsizeDialog.setActionValue(Type);
        customsizeDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag.equals("scene")) {
                    if (Type == 2) {
                        String result = customsizeDialog.checkSleep();
                        if (result == null) {
                            showToast(getString(R.string.activity_add_action_input_num));
                            return;
                        } else if (result.equals("True")) {
                        } else {
                            showToast(result);
                            return;
                        }
                    }
                    ActionBean actionBean = customsizeDialog.getActionValueByScene(deviceBean, Type);
                    sceneBean.getCommands().add(actionBean);
                    customsizeDialog.dismiss();
                    mHandler.sendEmptyMessage(EXIT);
                } else {
                    if (Type == 2) {
                        String result = customsizeDialog.checkSleep();
                        if (result == null) {
                            showToast(getString(R.string.activity_add_action_input_num));
                            return;
                        } else if (result.equals("True")) {
                        } else {
                            showToast(result);
                            return;
                        }
                    }
                    CommandBean commandBean = customsizeDialog.getActionValue(deviceBean, Type);
                    commandBeans.add(commandBean);
                    customsizeDialog.dismiss();
                    mHandler.sendEmptyMessage(EXIT);
                }
            }
        });
        customsizeDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if (Type == 2) {
                    showInputMethod();
                }
            }
        });
        customsizeDialog.show();
    }

    private void showInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_action_title));
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    public void onBackPressed() {
        exit();
    }

}
